from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.serializers.permissions import PermissionSerializer, ContentTypeSerializer, GroupSerializer, \
    PermissionSimpleSerializer, AdminSerializer
from users.models import User


class PermissionViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    #指定查询集合
    queryset = Permission.objects.all()

    # 指定视图所使用的序列化器类
    serializer_class = PermissionSerializer

    lookup_value_regex = '\d+'

    # GET `/meiduo_admin/permission/content_types/`
    # @action(methods=['get'],detail=False)
    def content_types(self,request):

        """
        获取权限类型数据
        1.获取权限类型数据
        2.将权限类型数据序列化返回
        :param request:
        :return:
        """
        #1.获取权限类型数据
        content_types = ContentType.objects.all()

        #2.将权限类型数据序列化返回
        serializer = ContentTypeSerializer(content_types,many=True)
        return Response(serializer.data)


class GroupViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    #指定视图所使用的查询集合
    queryset = Group.objects.all()

    #指定序列化器类
    serializer_class = GroupSerializer
    # GET `/meiduo_admin/permission/simple/`
    def simple(self,request):
        """
        获取权限数据
        1.获取权限数据
        2.将权限数据序列化并返回
        :param request:
        :return:
        """
        #1.获取权限数据
        permissions = Permission.objects.all()

        #将权限数据序列化并返回
        serializer = PermissionSimpleSerializer(permissions,many=True)
        return Response(serializer.data)


class AdminViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    #指定视图所使用的查询集合
    queryset = User.objects.filter(is_staff=True)

    #指定视图所使用的序列化器类
    serializer_class = AdminSerializer
    lookup_value_regex = '\d+'
    # GET /meiduo_admin/permission/groups/simple/
    def simple(self,request):
        """
        获取用户组数据
        1.获取管理员用户组数据
        2.将管理员用户组数据序列化并返回
        :param request:
        :return:
        """
        #1.获取用户组数据
        groups = Group.objects.all()

        #2.将用户组数据序列化并返回
        serializer = GroupSerializer(groups,many=True)
        return Response(serializer.data)

